﻿//表单插件类

define(function (require, exports, module) {
    require('./ActionJScript');
    require('./jshint');
    require('./FormXMLParser');
    var CForm_PageEventHandler = require('./FormPageEvent');
    //var CForm_MousePtHandler = require('./FormMousePtHandler');
    var CForm_DocViewEventHandler = require('./FormDocViewEventHandler');
    FXREADER.CFormPlugin = function (pReaderApp) {
        var _pReaderApp = pReaderApp,
            _Language = _pReaderApp.GetLanguage(),
            _self = this,
            _mPopupExportDlg = null;

        this.m_bCanFillForm = false;
        this.m_bHighlight = true;
        this.m_Pages = new Array();
        this.m_PagesVisable = new Array();
        this.m_PagesNeedShow = new Array();
        this.m_PagesRequest = new Array();

        //获取Plugin名称;
        this.GetPluginName = function () {
            return "Form Plugin";
        };
        //插件被注册的时候调用;
        this.PIOnRegister = function () {
        };

        this.GetLanguage = function () {
            return _Language;
        };
        //模块初始化;
        this.PIInit = function () {
            var docType = _pReaderApp.GetPDFDoc().GetDocType();
            if (docType != FXREADER.PDFData.DocType.FORM && docType != FXREADER.PDFData.DocType.XFA)
                return;
            var docPemission = _pReaderApp.GetDocPemission();
            this.m_bCanFillForm = (docPemission & 0x0010) == 0;

            _self.CreateCmdAndCmdUI();
            if (this.m_bCanFillForm) {
                var pFormPageEventHandler = new CForm_PageEventHandler(_self);
                _pReaderApp.RegisterPageEventHandler(pFormPageEventHandler);
                //var ptenvent = new CForm_MousePtHandler(this);
                //_pReaderApp.RegisterMousePtHandler(ptenvent);
                var pFormDocViewEventHandler = new CForm_DocViewEventHandler(_self);
                _pReaderApp.RegisterDocViewEventHandler(pFormDocViewEventHandler);

                this.showFormWidget();
            }
        };
        //模块卸载;
        this.PIUnload = function () {
        };
        //
        this.GetReaderApp = function () {
            return _pReaderApp;
        };
        //
        this.CreateCmdAndCmdUI = function () {
            //添加导出数据按钮
            _pReaderApp.AddCommandUI({
                UIName: "ExportData",
                CommandName: null,
                CreateHtmlContentFunc: function () {
                    return "<a id='btnExportData' class='fwr_toobar_export_data_dis fwr_toobar_image_btn' title='" + _Language.Form.ExportDataButTitle + "'></a>";
                },
                Init: function () {
                    if (!_self.m_bCanFillForm)
                        return;
                    FXREADER.Common.UpdateBtnState('btnExportData', "fwr_toobar_export_data_nor", "fwr_toobar_export_data_dis", true);
                    $("#btnExportData").bind('click', function () {
                        if ($("#btnExportData").hasClass("fwr_toobar_export_data_nor")) {
                            if (_mPopupExportDlg == null) {
                                var formMenuobj = $('<div id="exportFormat" title="' + _Language.Form.ExportDataDlgTitle + '" class="fwr_dialog fwr_hidden"></div>');
                                var tableObj = $('<table class="fwr_export_data_table"></table>');
                                var tr1 = $('<tr></tr>');
                                tr1.append($('<td class="fwr_export_data_td1"><input type="radio" value="pdf" name="format" class="fwr_export_data_radio" checked="checked" /></td>'));
                                tr1.append($('<td class="fwr_export_data_td2"><div class="fwr_export_data_div_top">' + _Language.Form.ExportDataPDFFormat + '</div><div class="fwr_export_data_div_bottom">' + _Language.Form.ExportDataPDFNote + '</div></td>'));
                                tableObj.append(tr1);
                                tableObj.append($('<tr><td colspan="2" class="fwr_export_data_tr_td"></td></tr>'));
                                var tr2 = $('<tr></tr>');
                                tr2.append($('<td class="fwr_export_data_td1"><input type="radio" value="fdf" name="format" class="fwr_export_data_radio" /></td>'));
                                tr2.append($('<td class="fwr_export_data_td2"><div class="fwr_export_data_div_top">' + _Language.Form.ExportDataFDFFormat + '</div><div class="fwr_export_data_div_bottom">' + _Language.Form.ExportDataFDFNote + '</div></td>'));
                                tableObj.append(tr2);
                                tableObj.append($('<tr><td colspan="2" class="fwr_export_data_tr_td"></td></tr>'));
                                var tr3 = $('<tr></tr>');
                                tr3.append($('<td class="fwr_export_data_td1"><input type="radio" value="xml" name="format" class="fwr_export_data_radio" /></td>'));
                                tr3.append($('<td class="fwr_export_data_td2"><div class="fwr_export_data_div_top">' + _Language.Form.ExportDataXMLFormat + '</div><div class="fwr_export_data_div_bottom">' + _Language.Form.ExportDataXMLNote + '</div></td>'));
                                tableObj.append(tr3);
                                tableObj.append($('<tr style="text-align: right;"><td colspan="2" class="fwr_export_data_td_choice"><input type="button" id="btnExportDataCancel" class="fwr_export_data_btn_cancel" value="' + _Language.Form.ExportDataDlgBut_Cancel + '" /><input type="button" id="btnExportDataOk" value="' + _Language.Form.ExportDataDlgBut_Ok + '" class="fwr_export_data_btn_ok" /></td></tr>'));
                                var childObj = $('<div style="padding: 12px; padding-bottom: 0px;"></div>');
                                childObj.append(tableObj);
                                formMenuobj.append(childObj);
                                $("body").append(formMenuobj);

                                $("#btnExportDataCancel").bind("click", function () {
                                    _mPopupExportDlg.dialog('close');
                                });
                                $("#btnExportDataOk").bind("click", function () {
                                    _mPopupExportDlg.dialog('close');
                                    _self.ExportData($('input[name="format"]:checked').val());
                                });

                                _mPopupExportDlg = $('#exportFormat').dialog({
                                    autoOpen: false,
                                    width: 500,
                                    modal: true,
                                    position: 'center',
                                    closeText: ''
                                });
                            }
                            _mPopupExportDlg.dialog("open");
                            return false;
                        }
                    });
                }
            });
            //添加高亮显示按钮
            _pReaderApp.AddCommandUI({
                UIName: "Highlight",
                CommandName: null,
                CreateHtmlContentFunc: function () {
                    return "<a id='btnHighlight' style='margin-right:4px;height:25px;' class='fwr_toolbar_link_btn fwr_form_highlight_btn_dis' title='" + _Language.Form.HighlightButTitle + "'>" +
                           "<img src='about:blank' style='height:10px;width:10px;margin:8px 4px 0px 0px;float:left;'/>" + _Language.Form.HighlightButText + "</a>";
                },
                Init: function () {
                    if (!_self.m_bCanFillForm) {
                        obj.children("img").addClass("fwr_form_highlight_btn_img_dis");
                        return;
                    }
                    var obj = $("#btnHighlight");
                    obj.children("img").addClass("fwr_form_highlight_btn_img");
                    obj.removeClass('fwr_form_highlight_btn_dis').addClass('fwr_toolbar_btn').bind('click', function () {
                        _self.ChangeHighlight();
                        return false;
                    });
                }
            });
        };

        this.ExportData = function (type) {
            var formData = FXREADER.g_formValue.GetFormDataXML();
            var fileID = _pReaderApp.GetFileID();
            //fileID = encodeURIComponent(fileID);
            var obj = $("#exportFormData");
            if (obj) {
                obj.remove();
            }
            var formobj = $('<form target="_self"></form>').attr("action", FXREADER.Config.Url.ExportFormData).attr("id", "exportFormData").attr("method", "post");
            formobj.append($("<input type='hidden' id='filetype' name='filetype' />").val(type));
            formobj.append($("<input type='hidden' id='fileid' name='fileid' />").val(fileID));
            formobj.append($("<input type='hidden' id='formdata'name='formdata' />").val(escape(formData)));
            $("body").append(formobj);
            formobj.submit();
        };

        this.ChangeHighlight = function () {
            //按钮样式改变
            this.m_bHighlight = !this.m_bHighlight;
            var classNameAdd = this.m_bHighlight ? "fwr_form_highlight_btn_img" : "fwr_form_highlight_btn_img_2";
            var classNameRemove = this.m_bHighlight ? "fwr_form_highlight_btn_img_2" : "fwr_form_highlight_btn_img";
            $("#btnHighlight").children("img").addClass(classNameAdd);
            $("#btnHighlight").children("img").removeClass(classNameRemove);
            for (key in this.m_Pages) {
                if (this.m_Pages[key] == null)
                    continue;
                this.m_Pages[key].ChangeHighlight(this.m_bHighlight);
            }
        };

        function ErrorResults(state, errMsg) {
            this.m_state = state;
            this.m_errMsg = errMsg;
        }
        function checkError(xmlData) {
            var ret = null;
            if (xmlData == null) {
                return "Loading failed, the link is corrupted or tampered.";
            }
            $(xmlData).find("Pages").each(function () {
                if (FXREADER.GetNodeString($(this), "Error") == "Error") {
                    var errMsg = FXREADER.GetNodeString($(this), "Msg");
                    var state = FXREADER.GetNodeFloat($(this), "status");
                   // var progress  = FXREADER.GetNodeFloat($(this), "progress");
                    ret = new ErrorResults(state, errMsg);
                }
            });
            return ret;
        }

        this.AjaxGetFormXml = function (pageNumArr, retryCount,retryInterval) {
            var fileID = _pReaderApp.GetFileID();
            var pageNumsStr = pageNumArr.join(";");
            var data = { fileid: fileID, page: pageNumsStr };
            if (retryCount <= 0) {
                throw new Error('Maximum number of retries exceeded for GetFormXml request.');
            }

            $.ajax({
                type: "post",
                url: FXREADER.Config.Url.GetFormXml,
                dataType: 'xml',
                data: data,
                success: function (xmlData) {
                    var errorResults = checkError(xmlData);
                    if (errorResults) {
                        if (FXREADER.Common.IsNeedRetry(errorResults.m_state)) {
                        	var progress = _pReaderApp.GetMainView().GetDocView().GetPageViewRender().getMaxRenderedPageIndex();
                        	if(progress == null)
                        		progress = 0;
                           
                            var interval = FXREADER.AjaxRetryManager.GetNextFormXmlRequestInterval(pageNumArr[pageNumArr.length-1],progress,
                            		_pReaderApp.GetMainView().GetDocView().GetPageCount());
                            setTimeout(function () { _self.AjaxGetFormXml(pageNumArr, retryCount - 1); },interval);
                            return;
                        }
                        else if (errorResults.m_errMsg != "") {
                            for (var i in pageNumArr)
                                _self.m_PagesVisable[pageNumArr[i]] = false;
                            throw new Error('Get Form XML Data Error:' + errorResults.m_errMsg);
                            return;
                        }
                    }

                    var pDocView = _pReaderApp.GetMainView().GetDocView();
                    $(xmlData).find("Page").each(function () {
                        var pageIndex = parseInt($(this).attr("PageNo"));
                        var pageView = pDocView.GetPageView(pageIndex);
                        var pageID = pageView.GetPageBGImgID();
                        var tmpformPage = new FXREADER.FormPage();
                        if (!_self.m_Pages[pageIndex]) {
                            tmpformPage.Parser(pageID + "_form", pageIndex, "fileid=" + encodeURIComponent(fileID), $(this));
                            _self.m_Pages[pageIndex] = tmpformPage;
                            if (pageView.IsPageLoaded()) {
                                if (pageView.IsPageLoadError()) {
                                    _self.m_Pages[pageIndex] = null;
                                }
                                else {
                                    $("#" + pageID).after(tmpformPage.GetHtmlCode(_self.m_bHighlight));
                                    tmpformPage.GetRegisterActionCode();
                                    tmpformPage.GetReadyBindCode();
                                    if (_self.m_PagesVisable[pageIndex] == true)
                                        tmpformPage.ShowPage();
                                    tmpformPage.ChangeSize(pDocView.GetScale());
                                    _self.m_Pages[pageIndex].ChangeHighlight(_self.m_bHighlight);
                                }
                            }
                            else {
                                _self.m_PagesNeedShow[pageIndex] = true;
                            }
                        }
                        pageNumArr[pageIndex] = null;
                        _self.m_PagesRequest[pageIndex] = false;
                    });

                    for (var i in pageNumArr) {
                        if (pageNumArr[i] != null) {
                            _self.m_PagesVisable[pageNumArr[i]] = false;
                        }
                    }
                },
                error: function () {
                    for (var i in pageNumArr)
                        _self.m_PagesVisable[pageNumArr[i]] = false;
                    throw new Error('Get Form XML Data Error!');
                }
            });
        };

        this.showFormWidget = function () {
            var pDocView = _pReaderApp.GetMainView().GetDocView();
            var visablePageRange = pDocView.GetDisplayPageRange();
            var pageNumArr = new Array();
            var pageCount = 0;
            for (var i = visablePageRange.begin; i <= visablePageRange.end; i++) {
                var pPageView = pDocView.GetPageView(i);
                if (!pPageView.IsPageLoadError()) {
                    if (this.m_Pages[i]) {
                        if (this.m_PagesVisable[i] == false) {
                            this.m_Pages[i].ShowPage();
                            this.m_PagesVisable[i] = true;
                        }
                    }
                    else {
                        this.m_PagesVisable[i] = true;
                        if (this.m_PagesRequest[i] != true) {
                            this.m_PagesRequest[i] = true;
                            pageNumArr[pageCount++] = i;
                        }
                    }
                }
            }
            if (pageNumArr.length > 0) {
                this.AjaxGetFormXml(pageNumArr, FXREADER.Config.requestRetryCount);
            }
        };

        //PageEvent 消息响应;
        this.OnPageVisible = function (pPageView, contentPanelWidth, contentPanelHeight, contentPanelOffset) {
            this.showFormWidget();
            return true;
        };

        this.OnPageShowComplete = function (pPageView) {
            var iPageIndex = pPageView.GetPageIndex();
            if (this.m_PagesNeedShow[iPageIndex] == true) {
                if (pPageView.IsPageLoadError()) {
                    this.m_Pages[iPageIndex] = null;
                }
                else {
                    var formPage = this.m_Pages[iPageIndex];
                    var pageID = pPageView.GetPageBGImgID();
                    this.m_PagesNeedShow[iPageIndex] = false;
                    $("#" + pageID).after(formPage.GetHtmlCode(this.m_bHighlight));
                    formPage.GetRegisterActionCode();
                    formPage.GetReadyBindCode();
                    if (_self.m_PagesVisable[iPageIndex] == true)
                        formPage.ShowPage();
                    formPage.ChangeSize(pPageView.GetDocView().GetScale());
                }
            }
            return true;
        };

        this.OnPageInvisible = function (pPageView) {
            var iPageIndex = pPageView.GetPageIndex();
            this.m_PagesVisable[iPageIndex] = false;
            return true;
        };

        //Doc View 消息响应
        this.OnPreDocViewResize = function () {
            var scale = _pReaderApp.GetMainView().GetDocView().GetScale();
            for (key in this.m_Pages) {
                if (this.m_Pages[key] == null)
                    continue;
                this.m_Pages[key].ChangeSize(scale);
            }
        };

        this.OnDocViewResize = function () {
        };

        this.OnDocViewScroll = function () {
        };

        this.OnDocViewZoom = function (scale) {
        };

        this.OnPageIndexUpdated = function (iPageIndex) {
            this.showFormWidget();
        };
    };


    exports.Reader_CreatePlugin = function (pReaderApp) {
        var pFormPlugin = new FXREADER.CFormPlugin(pReaderApp);
        FXREADER.g_pFormPlugin = pFormPlugin;
        FXREADER.g_formValue = new FXREADER.FormValue();
        return pFormPlugin;
    };

});